package com.guyaogg.gulimall.product.web;

import com.guyaogg.gulimall.product.entity.CategoryEntity;
import com.guyaogg.gulimall.product.service.CategoryService;
import com.guyaogg.gulimall.product.vo.Catalog2VO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 顾遥
 */
@Slf4j
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        // TODO 1.查出所有的 1 级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    /**
     * index/catalog.json
     */
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catalog2VO>> getCatalogJson() {

        return categoryService.getCatalogJson();
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        // 1.调用 redisson 获取锁，只要锁名一样就是同一把锁
        RLock lock = redisson.getLock("my-lock");

        // 2.加锁
        // 获取锁 , 默认是看门狗默认 10 s 自动续机 30 s，自己设置时间的没有看门狗,一般使用自己设置时间，省掉续期业务
        lock.lock(10, TimeUnit.SECONDS); // 阻塞式等待
        // 锁的自动续机，如果业务超长，自动给锁 30 s
        // 不在机就会过期解锁
        try {
            // 临界区
            log.info("加锁成功，执行业务..." + Thread.currentThread().getId());
            Thread.sleep(30000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            lock.unlock();
            System.out.println("释放锁..." + Thread.currentThread().getId());
        }

        return "hello";
    }

}
